package auth

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gitee.com/xiaofengfeng123/srv-paper-tape/api/response"
	"gitee.com/xiaofengfeng123/srv-paper-tape/errors"
	"gitee.com/xiaofengfeng123/srv-paper-tape/utils"
	"net/http"
)

func AuthRoute(parentRoute *gin.RouterGroup){
	router := parentRoute.Group("/auth")
	s := NewService()
	router.GET("/login",makeLoginEndPoint(s))
	router.GET("/openid",makeGetOpenidEndPoint(s))
}

func makeLoginEndPoint(s Service)func (ctx *gin.Context){
	return func(ctx *gin.Context) {
		user,err := s.Login(ctx.Query("code"),ctx.Query("rawData"),ctx.Query("encryptedData"),ctx.Query("signature"),ctx.Query("iv"))
		if err !=nil{
			response.JSON(ctx,http.StatusInternalServerError,nil,errors.ErrLogin)
			return
		}



		c := utils.NewClaims(user.Id)
		err = utils.SetHeaderClaims(ctx,c)
		if err !=nil{
			logrus.Errorf(err.Error())
			response.JSON(ctx,http.StatusInternalServerError,nil,errors.ErrLogin)
			return
		}
		response.JSON(ctx,http.StatusOK,user,errors.OK)
		return
	}
}

func makeGetOpenidEndPoint(s Service)func (ctx *gin.Context){
	return func(ctx *gin.Context) {
		user,err := s.GetOpenid(ctx.Query("code"))
		if err !=nil{
			response.JSON(ctx,http.StatusInternalServerError,nil,errors.ErrLogin)
			return
		}
		c := utils.NewClaims(user.Id)
		err = utils.SetHeaderClaims(ctx,c)
		if err !=nil{
			logrus.Errorf(err.Error())
			response.JSON(ctx,http.StatusInternalServerError,nil,errors.ErrLogin)
			return
		}
		response.JSON(ctx,http.StatusOK,user,errors.OK)
		return
	}
}


